package jhc.cn.moviegallery;

import android.content.Context;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by luyanfei on 16-11-29.
 */

public class QueryPreferences {
    private static final String TAG = QueryPreferences.class.getName();
    private static final String PREF_SEARCH_QUERY = "searchQuery";
    private static final String PREF_THEATERS_DIGEST = "in_theaters_title_md5";

    public static String getStoredQuery(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(PREF_SEARCH_QUERY, null);
    }

    public static void setStoredQuery(Context context, String query) {
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(PREF_SEARCH_QUERY, query)
                .apply();
    }

    public static String getStoredTitlesDigest(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(PREF_THEATERS_DIGEST, null);
    }

    public static void setStoredTitlesDigest(Context context, List<GalleryItem> items) {
        String digestString = computeMd5(items);
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(PREF_THEATERS_DIGEST, digestString)
                .apply();
    }

    /**
     * 把获取的电影标题排序，拼接所有标题，计算出该字符串的MD5,通过MD5值的变化来检测是否有新电影上映。
     * @param items
     * @return
     */
    public static String computeMd5(List<GalleryItem> items) {
        List<String> titles = new ArrayList<>();
        for(GalleryItem it : items) {
            titles.add(it.toString());
        }
        Collections.sort(titles, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        StringBuilder builder = new StringBuilder();
        for(String t : titles) {
            builder.append(t);
        }

        byte[] data = builder.toString().getBytes();
        MessageDigest md5Digest;
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "MD5 algorithm not find.", e);
            return null;
        }
        byte[] digestResult = md5Digest.digest(data);
        return Base64.encodeToString(digestResult, Base64.DEFAULT);
    }
}
